package com.example.security;

import cn.hutool.json.JSONUtil;
import com.example.common.result.Result;
import com.example.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component //用户退出处理器
public class JwtLogoutSuccessHandler implements LogoutSuccessHandler {

    @Autowired
    JwtUtil jwtUtil;
    
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        //当authentication不为空，手动退出
        if (authentication != null) {
            SecurityContext context = SecurityContextHolder.getContext();
            context.setAuthentication((Authentication) null);
        }

        //设置返回类型和字符编码
        response.setContentType("application/json;charset=UTF-8");
        //定义一个response输出流
        ServletOutputStream outputStream = response.getOutputStream();

        response.setHeader(jwtUtil.getHeader(), "");

        //将jwt封装成Result
        Result result = Result.ok().message("退出成功");

        //将result写入输出流中
        outputStream.write(JSONUtil.toJsonStr(result).getBytes("UTF-8"));
        //刷新此输出流并强制写出所有缓冲的输出字节
        outputStream.flush();
        //将输出流关闭
        outputStream.close();
    }
}
